/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: FingerActivity.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.safe.fingerprint;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.hardware.fingerprint.FingerprintManagerCompat;
import android.support.v4.os.CancellationSignal;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.github.ybq.android.spinkit.style.Wave;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import io.bhex.app.R;
import io.bhex.app.safe.bean.FingerSwitcher;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.NetWorkStatus;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.core.SPEx;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.Utils.CookieUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.network.response.ResultResponse;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.account.EventLogin;
import io.bhex.sdk.account.LoginApi;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.account.bean.UserInfoBean;
import io.bhex.sdk.data_manager.NetWorkApiManager;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.data_manager.TradeDataManager;

/**
 * ================================================
 * 描   述：指纹识别
 * ================================================
 */

public class FingerActivity extends Activity implements View.OnClickListener{
    private static final long ERROR_TIMEOUT_MILLIS = 1600;
    private static final long SUCCESS_DELAY_MILLIS = 1300;
    FingerprintManagerCompat manager;
    KeyguardManager mKeyManager;
    private final static int REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS = 0;
    private final static String TAG = "finger_log";
    private TextView tipTx;
    private TextView btn_finger;
    private ImageView fingerIcon;
    private TextView usernameTx;
    private String caller="";
    private Dialog dialog;
    private int dialogRef;
    private boolean isAlive = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_finger_layout);
//        manager = (FingerprintManager) this.getSystemService(Context.FINGERPRINT_SERVICE);
        manager = FingerprintManagerCompat.from(this);

        Intent intent = getIntent();
        if (intent != null) {
            caller = intent.getStringExtra(AppData.INTENT.LOGIN_CALLER);
            if (caller.equals(AppData.INTENT.FINGER_CALLER_SECURITY)) {
                findViewById(R.id.btn_passwd_login).setVisibility(View.GONE);
            }else {
                findViewById(R.id.btn_passwd_login).setVisibility(View.VISIBLE);
            }
        }

        usernameTx = findViewById(R.id.username);
        tipTx = findViewById(R.id.fingerprint_description);
        fingerIcon = findViewById(R.id.fingerprint_icon);
        mKeyManager = (KeyguardManager) this.getSystemService(Context.KEYGUARD_SERVICE);
        this.findViewById(R.id.btn_passwd_login).setOnClickListener(this);

        btn_finger = findViewById(R.id.btn_finger);
        btn_finger.setOnClickListener(this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        UserInfoBean userInfo = UserInfo.getUserInfo();
        if (userInfo != null) {
            int registerType = userInfo.getRegisterType();
            if (registerType==1) {
                usernameTx.setText(userInfo.getMobile());
            }else{
                usernameTx.setText(userInfo.getEmail());
            }

        }
        startAuthFingerPrint();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_passwd_login:
                //清除密码
                SPEx.set(AppData.SPKEY.GESTURE_PWD_KEY,"");

                SPEx.setFingerAuth(false);
//                SPEx.removeFingerOpen();
                UserInfo.clearUserInfo();
                CookieUtils.clearCookies(FingerActivity.this);
                logout();
                IntentUtils.goLogin(this,"");
                this.finish();
                break;
            case R.id.btn_finger:
                startAuthFingerPrint();
                break;
        }
    }


    private void startAuthFingerPrint() {
        if (isFinger()) {
//            Toast.makeText(FingerActivity.this, getString(R.string.fingerprint_identify_hint), Toast.LENGTH_LONG).show();
            Log(TAG, getString(R.string.fingerprint_identify_hint));
            startListening(null);
        }
    }

    public boolean isFinger() {

        //android studio 上，没有这个会报错
        if (ActivityCompat.checkSelfPermission(FingerActivity.this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, getString(R.string.string_no_fingerprint_permission), Toast.LENGTH_SHORT).show();
            return false;
        }
        Log(TAG, "有指纹权限");
        //判断硬件是否支持指纹识别
        if (!manager.isHardwareDetected()) {
            Toast.makeText(this, getString(R.string.fingerprint_no_hardware), Toast.LENGTH_SHORT).show();
            return false;
        }
        Log(TAG, "有指纹模块");
        //判断 是否开启锁屏密码
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            if (!mKeyManager.isKeyguardSecure()) {
                Toast.makeText(this, getString(R.string.fingerprint_no_lock_screen_pwd), Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        Log(TAG, "已开启锁屏密码");
        //判断是否有指纹录入
        if (!manager.hasEnrolledFingerprints()) {
            Toast.makeText(this, getString(R.string.fingerprint_create_finger_first_hint), Toast.LENGTH_SHORT).show();
            return false;
        }
        Log(TAG, "已录入指纹");

        return true;
    }

    CancellationSignal mCancellationSignal = new CancellationSignal();
    //回调方法
    FingerprintManagerCompat.AuthenticationCallback mSelfCancelled = new FingerprintManagerCompat.AuthenticationCallback() {
        @Override
        public void onAuthenticationError(int errorCode, CharSequence errString) {
            //但多次指纹密码验证错误后，进入此方法；并且，不能短时间内调用指纹验证
//            errorCode 5 指纹设置取消  7 指纹次数过多
            DebugLog.e(errorCode+"  指纹======   "+errString.toString());
            if (errorCode==7) {
                showError(getString(R.string.string_fingerprint_errors_retry));
                if(!caller.equals(AppData.INTENT.FINGER_CALLER_SECURITY)){

                    boolean fingerOpen = SPEx.isFingerOpen();
                    if (fingerOpen){
                        SPEx.removeFingerOpen();
                        SPEx.setFingerAuth(false);
                    }
                    UserInfo.clearUserInfo();
                    CookieUtils.clearCookies(FingerActivity.this);
                    IntentUtils.goLogin(FingerActivity.this,"");
                    finish();
                }else{
                    ToastUtils.showLong(FingerActivity.this, getString(R.string.string_finger_set_failed));
                    finish();
                }
            }
            //系统密码
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                showAuthenticationScreen();
//            }
        }

        @Override
        public void onAuthenticationHelp(int helpCode, CharSequence helpString) {
            showError(helpString);
        }

        @Override
        public void onAuthenticationSucceeded(FingerprintManagerCompat.AuthenticationResult result) {
            showAuthenticationSucceeded(result);
        }

        @Override
        public void onAuthenticationFailed() {
            showError(getString(R.string.fingerprint_failed));
        }
    };


    public void startListening(FingerprintManagerCompat.CryptoObject cryptoObject) {
        //android studio 上，没有这个会报错
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, getString(R.string.string_no_fingerprint_permission), Toast.LENGTH_SHORT).show();
            return;
        }
        manager.authenticate(cryptoObject, 0,mCancellationSignal, mSelfCancelled, null);


    }

    /**
     * 锁屏密码
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void showAuthenticationScreen() {

        Intent intent = mKeyManager.createConfirmDeviceCredentialIntent("finger", getString(R.string.string_fingerprint_identify));
        if (intent != null) {
            startActivityForResult(intent, REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS) {
            // Challenge completed, proceed with using cipherO
            if (resultCode == RESULT_OK) {
                Toast.makeText(this, getString(R.string.fingerprint_success), Toast.LENGTH_SHORT).show();
                AppData.isFirstLaunch=false;
                AppData.isHome=false;
                finish();
            } else {
                showError(getString(R.string.fingerprint_failed));
            }
        }
    }

    public void showAuthenticationSucceeded(FingerprintManagerCompat.AuthenticationResult result) {
//        Toast.makeText(FingerActivity.this, getString(R.string.fingerprint_success), Toast.LENGTH_SHORT).show();

        boolean bNet = NetWorkStatus.isConnected(FingerActivity.this);
        if (!bNet) {
            ToastUtils.showLong(FingerActivity.this, getResources().getString(R.string.hint_network_not_connect));
            startAuthFingerPrint();
            return;
        }

        tipTx.removeCallbacks(mResetErrorTextRunnable);
        fingerIcon.setImageResource(R.drawable.ic_fingerprint_success);
        tipTx.setTextColor(
                tipTx.getResources().getColor(R.color.green));
        tipTx.setText(
                tipTx.getResources().getString(R.string.fingerprint_success)+ "," + getResources().getString(R.string.fingerprint_login));

        LoginApi.autoCheckToken(FingerActivity.this,0,new SimpleResponseListener<ResultResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
                showProgressDialog("","");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                dismissProgressDialog();
            }

            @Override
            public void onSuccess(ResultResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    if (response.isSuccess()) {
                        LoginApi.GetUserInfo();
                        SPEx.setFingerAuth(true);

                        AppData.isHome=false;

                        if (caller.equals("")) {
//                            ActivityCache.getInstance().finishActivity();
//                            IntentUtils.goMain(FingerActivity.this);
                        }else if(caller.equals(AppData.INTENT.LOGIN_CALLER_TRADE)||caller.equals(AppData.INTENT.LOGIN_CALLER_TAB_ACCOUNT)){
                            //finish();
                        }
                        else if(caller.equals(AppData.INTENT.LOGIN_CALLER_WEB) || caller.equals(AppData.INTENT.LOGIN_CALLER_MAIN)){
                            setResult(RESULT_OK);
                            //finish();
                        }else if(caller.equals(AppData.INTENT.FINGER_CALLER_SECURITY)){
                            Intent intent = new Intent();
                            FingerSwitcher fingerSwitcher = new FingerSwitcher();
                            fingerSwitcher.setAuthSuccess(true);
                            intent.putExtra("fingerauth",fingerSwitcher);
                            setResult(RESULT_OK,intent);
                        }
                        finish();
                        TradeDataManager.GetInstance().release();
                        NetWorkApiManager.releaseTradeInstance();
                        NetWorkApiManager.getTradeInstance();
                        SymbolDataManager.GetInstance().getFavorites();

                    }else{
                        //TODO 续期失败1
                        boolean fingerOpen = SPEx.isFingerOpen();
                        if (fingerOpen){
                            SPEx.setFingerAuth(false);
                        }
                        UserInfo.clearUserInfo();
                        CookieUtils.clearCookies(FingerActivity.this);
                        IntentUtils.goLogin(FingerActivity.this,"");
                        finish();
                    }
                }else{
                    //TODO 续期失败2
//                    if (response.getCode().equals(ERROR_CODE.NO_LOGIN.getCode())) {
                        boolean fingerOpen = SPEx.isFingerOpen();
                        if (fingerOpen){
                            SPEx.setFingerAuth(false);
                        }
                        UserInfo.clearUserInfo();
                        CookieUtils.clearCookies(FingerActivity.this);
                        IntentUtils.goLogin(FingerActivity.this,"");
                        finish();
//                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                if(caller.equals(AppData.INTENT.FINGER_CALLER_SECURITY)){
                    ToastUtils.showLong(FingerActivity.this, getString(R.string.string_finger_set_failed));
                }else{
//                    ToastUtils.showLong(FingerActivity.this, getString(R.string.string_login_failed));
                    ToastUtils.showLong(FingerActivity.this, getString(R.string.string_net_exception));
                    startAuthFingerPrint();
//                    boolean fingerOpen = SPEx.isFingerOpen();
//                    if (fingerOpen){
//                        SPEx.setFingerAuth(false);
//                    }
//                    UserInfo.clearUserInfo();
//                    CookieUtils.clearCookies(FingerActivity.this);
//                    IntentUtils.goLogin(FingerActivity.this,"");
//                    finish();
                }
            }
        });

    }

    private void showError(CharSequence error) {
//        Toast.makeText(FingerActivity.this, error, Toast.LENGTH_SHORT).show();
        fingerIcon.setImageResource(R.drawable.ic_fingerprint_error);
        tipTx.setText(error);
        tipTx.setTextColor(
                tipTx.getResources().getColor(R.color.red));
        tipTx.removeCallbacks(mResetErrorTextRunnable);
        tipTx.postDelayed(mResetErrorTextRunnable, ERROR_TIMEOUT_MILLIS);
    }

    private Runnable mResetErrorTextRunnable = new Runnable() {
        @Override
        public void run() {
            tipTx.setText("");
            btn_finger.setText(getResources().getString(R.string.fingerprint_hint));
            fingerIcon.setImageResource(R.mipmap.icon_finger);
        }
    };

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode== KeyEvent.KEYCODE_BACK) {
//            return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    private void Log(String tag, String msg) {
        DebugLog.d(tag, msg);
    }


    public void showProgressDialog(String title, String hint) {
        if (!isAlive())
            return;

        dialogRef++;

        if (dialog != null && dialog.isShowing())
            return;


        if (dialog == null) {
            dialog = new Dialog(this, R.style.dialogLoading);
            dialog.setContentView(R.layout.loading_waiting_layout);
            ProgressBar progressBar = dialog.findViewById(R.id.bar_loading);
//        RotatingPlane animDrawable = new RotatingPlane();
//        DoubleBounce animDrawable = new DoubleBounce();
            Wave animDrawable = new Wave();
//        WanderingCubes animDrawable = new WanderingCubes();
//        Pulse animDrawable = new Pulse();
//        PulseRing animDrawable = new PulseRing();
//        ChasingDots animDrawable = new ChasingDots();
//        ThreeBounce animDrawable = new ThreeBounce();
//        Circle animDrawable = new Circle();
//        CircleSprite animDrawable = new CircleSprite();
//        FadingCircle animDrawable = new FadingCircle();
//        FoldingCube animDrawable = new FoldingCube();
//        RotatingCircle animDrawable = new RotatingCircle();
//                CubeGrid animDrawable = new CubeGrid();
            animDrawable.setColor(SkinColorUtil.getDark80(this));
            progressBar.setIndeterminateDrawable(animDrawable);
        }

        if (!TextUtils.isEmpty(title))
            dialog.setTitle(title);
        if (!TextUtils.isEmpty(hint))
            ((TextView) dialog.findViewById(R.id.loading_hint_text)).setText(hint);

        dialog.show();
    }

    public void dismissProgressDialog() {
        if (isAlive() && dialog != null && --dialogRef <= 0)
            dialog.dismiss();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        DebugLog.i(getClass().getSimpleName() + "------enter------");

        isAlive = false;
    }

    /**
     * Activity 是否还可用
     *
     * @return
     */
    public boolean isAlive() {
        return isAlive && !isFinishing();
    }

    /**
     * 退出
     */
    public void logout() {
        final boolean fingerOpen = SPEx.isFingerOpen();
        final String authKey = AppData.SPKEY.USER_AUTH_FINGER+UserInfo.getUserId();
        LoginApi.Logout(new SimpleResponseListener<ResultResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
                showProgressDialog("","");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                dismissProgressDialog();

                if (fingerOpen) {
                    SPEx.set(authKey, false);
                }
                MobclickAgent.onProfileSignOff();
                UserInfo.clearUserInfo();
                CookieUtils.clearCookies(FingerActivity.this);
                EventBus.getDefault().post(new EventLogin());
                FingerActivity.this.finish();
            }

            @Override
            public void onSuccess(ResultResponse response) {
//                if (fingerOpen) {
//                    SPEx.set(authKey, false);
//                }
//                MobclickAgent.onProfileSignOff();
//                UserInfo.clearUserInfo();
//                CookieUtils.clearCookies(FingerActivity.this);
//                EventBus.getDefault().post(new EventLogin());
//                FingerActivity.this.finish();
            }
            @Override
            public void onError(Throwable error){
            }
        });


    }
}
